package com.heroCW.bodhiAttic.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.heroCW.bodhiAttic.entity.Employee;
import com.heroCW.bodhiAttic.resultUtil.Result;
import com.heroCW.bodhiAttic.resultUtil.ResultCode;
import com.heroCW.bodhiAttic.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {

        // 根据username查询用户
        Employee emp = employeeService.getEmployeeByUsername(employee.getUsername());

        // 密码MD5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 用户不存在返回登陆失败结果
        if (emp == null) {
            return Result.error(ResultCode.USER_LOGIN_ERROR,"用户不存在，登陆失败");
        }

        // 密码比对
        if (!emp.getPassword().equals(password)) {
            return Result.error(ResultCode.USER_LOGIN_ERROR,"密码错误，登陆失败");
        }

        // 员工状态是否禁用
        if (emp.getStatus() == 0) {
            return Result.error(ResultCode.USER_LOGIN_ERROR,"您已被禁用，登陆失败");
        }

        // 登录成功，将员工id存入session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return Result.success(ResultCode.USER_LOGIN_SUCCESS, emp);
    }

    /**
     * 员工登出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return Result.success(ResultCode.USER_LOGOUT_SUCCESS, "退出成功");
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody Employee employee) {
        log.info("新增员工，员工信息：{}", employee.toString());

        // 设置初始密码123456，并进行MD5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        boolean flag = employeeService.save(employee);
        if (flag) {
            return Result.success(ResultCode.SAVE_OK,"新增员工成功");
        } else {
            return Result.error(ResultCode.SAVE_ERR,"新增员工失败");
        }

    }

    /**
     * 根据名字（非空）查询所有并分页
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<IPage<Employee>> page(int page, int pageSize, String name) {
        log.info("page={},pageSize={},name={}", page, pageSize, name);

        // 执行查询
        IPage<Employee> employeeIPage = employeeService.getPage(page, pageSize, name);

        if (employeeIPage!=null) {
            return Result.success(ResultCode.GET_OK, employeeIPage);
        }else {
        return Result.error(ResultCode.GET_ERR, "员工查询失败");
        }
    }

    /**
     * 根据id修改员工信息
     *
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody Employee employee) {
        log.info(employee.toString());

        boolean flag = employeeService.updateUser(employee);
        if (flag) {
            return Result.success(ResultCode.UPDATE_OK,"员工信息修改成功");
        } else {
            return Result.error(ResultCode.UPDATE_ERR,"员工信息修改失败");
        }
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id) {
        log.info("根据id查询员工信息");
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            return Result.success(ResultCode.GET_OK, employee);
        } else {
            return Result.error(ResultCode.GET_ERR,"没有查询到对应员工信息");
        }
    }
}
